package dbmethod

import (
	// "fmt"
	"photoPlugIn/config"
	us "photoPlugIn/utils"
	"strconv"
)

type photoDir struct {
	Id           int    `sqlField:"id" sqlType:"integer PRIMARY KEY autoincrement"`
	DirName      string `sqlField:"dirname" sqlType:"NVARCHAR(255)"`
	DirAliasName string `sqlField:"diraliasname" sqlType:"NVARCHAR(255)"`
	ParentId     int    `sqlField:"parentid" sqlType:"int(32)"`
	Source       string `sqlField:"source" sqlType:"NVARCHAR(255)"`
	FullDir      string `sqlField:"FullDir" sqlType:"CHAR(1)"`
}

func PhotoDirInsert(pid int64, dname string) int64 {
	db := config.CONFIG.Conn
	stmt, err := db.Prepare("INSERT INTO photodir(dirname, diraliasname, parentid,source) values(?,?,?,?)")
	us.CheckErr(err)
	res, err := stmt.Exec(dname, dname, pid, config.CONFIG.PHOTODB)
	us.CheckErr(err)
	id, err := res.LastInsertId()
	us.CheckErr(err)
	// fmt.Println(id)
	return id
}

func PhotoDirFind(ParentId int64, DirName string) *photoDir {
	// fmt.Println("测试查找...")
	db := config.CONFIG.Conn
	selectStr := "parentid=" + strconv.FormatInt(ParentId, 10) + " AND " + "dirname=" + "'" + DirName + "'" + " limit 0,1"
	// fmt.Println("sqlCmd:", "SELECT id,dirname,parentid FROM photodir WHERE "+selectStr)
	rows, err := db.Query("SELECT id,dirname,parentid FROM photodir WHERE " + selectStr)
	us.CheckErr(err)
	defer rows.Close()
	p := new(photoDir)
	for rows.Next() {
		err := rows.Scan(&p.Id, &p.DirName, &p.ParentId)
		us.CheckErr(err)
		// fmt.Println(p.Id, p.DirName, p.ParentId)
	}
	return p
}

func GetPhotoDirs(ParentId int64) []photoDir {
	// fmt.Println("测试查找...")
	db := config.CONFIG.Conn
	selectStr := "parentid=" + strconv.FormatInt(ParentId, 10)
	// fmt.Println("sqlCmd:", "SELECT id,dirname,parentid FROM photodir WHERE "+selectStr)
	rows, err := db.Query("SELECT id,dirname,parentid FROM photodir WHERE " + selectStr)
	us.CheckErr(err)
	defer rows.Close()
	p := []photoDir{}
	fori := 0
	for rows.Next() {
		id := 0
		dirName := ""
		Parentid := 0
		err := rows.Scan(&id, &dirName, &Parentid)
		p = append(p, photoDir{Id: id, DirName: dirName, ParentId: Parentid})
		us.CheckErr(err)
		fori++
		// fmt.Println(p.Id, p.DirName, p.ParentId)
	}
	return p
}
